package com.example.springstudy.controller;

import com.example.springstudy.base.Result;
import com.example.springstudy.entity.User;
import com.example.springstudy.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    UserService userService;


    @GetMapping("hello")
    public String hello(){
        return "hello!";
    }

    @Operation(summary = "查询所有用户列表")
    @GetMapping("/userList")
    public Result<?> getUserList(
            @RequestParam(required = false, defaultValue = "1") int page,
            @RequestParam(required = false, defaultValue = "10") int size){
        return Result.success(userService.getUserList(page, size));
    }

    @Operation(summary = "查询用户信息")
    @GetMapping("/info")
    public Result<User> getUser(@RequestParam Integer userId){
        return Result.success(userService.getUser(userId));
    }

    @Operation(summary = "添加或修改用户信息")
    @PostMapping("add")
    public Result<Boolean> saveUser(@RequestBody User user){
        log.info("user: {}", user);
        return Result.success(userService.addUser(user));
    }

    @Operation(summary = "删除用户")
    @DeleteMapping("delete")
    public Result<Boolean> deleteUser(Integer userId){
        return Result.success(userService.deleteUser(userId));
    }

    @GetMapping("/search")
    public Result<List<User>> searchUser(
            @RequestParam(required = false, defaultValue = "0") int type,
            @RequestParam String key){
        try{
            Assert.hasText(key, "key must not be empty");
            return Result.success(userService.searchUser(type, key));
        } catch (Exception e) {
            return Result.failed(e.getMessage());
        }

    }
}
